using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

public class RemoteDesktopManager
{
    public async Task<RemoteConnectionResult> ConnectAndLoadIISServices(RemoteMachine machine, IProgress<string> progress)
    {
        var result = new RemoteConnectionResult
        {
            Machine = machine,
            IsConnected = false
        };

        try
        {
            progress?.Report($"正在连接到 {machine.IPAddress}:{machine.Port}...");

            using var client = new HttpClient();
            client.Timeout = TimeSpan.FromSeconds(10);

            var apiUrl = $"http://{machine.IPAddress}:{machine.Port}/api/iis/sites";
            progress?.Report($"正在访问: {apiUrl}");

            var response = await client.GetAsync(apiUrl);

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var sites = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RemoteIISService>>(json);

                if (sites != null)
                {
                    result.IISServices = sites;
                    result.IsConnected = true;
                    progress?.Report($"成功获取 {sites.Count} 个IIS站点");
                }
            }
            else
            {
                result.ErrorMessage = $"HTTP请求失败: {response.StatusCode}\n\n解决方案:\n1. 在远程主机 {machine.IPAddress} 上运行AutoUpdater\n2. 确保远程AutoUpdater正在运行\n3. 确保端口 {machine.Port} 未被防火墙阻止";
                progress?.Report(result.ErrorMessage);
            }
        }
        catch (HttpRequestException ex)
        {
            result.ErrorMessage = $"无法连接到远程服务\n\n{ex.Message}\n\n请确保:\n1. 远程主机 {machine.IPAddress} 上运行了AutoUpdater\n2. 防火墙允许端口 {machine.Port}";
            progress?.Report(result.ErrorMessage);
        }
        catch (Exception ex)
        {
            result.ErrorMessage = $"连接失败: {ex.Message}";
            progress?.Report(result.ErrorMessage);
        }

        return result;
    }

    public async Task<bool> RemoteUpdateIISService(RemoteMachine machine, RemoteIISService service, string productName, string targetVersion, IProgress<string> progress)
    {
        return await Task.FromResult(false);
    }
}
